<template>
	<view class="smart-tabbar" v-if="shouldShow">
		<!-- 权限0：旧版3个tab -->
		<view v-if="tabbarConfig.permission === 0" class="tabbar classic-theme">
			<view class="tabbar-container">
				<view 
					v-for="(tab, index) in tabbarConfig.tabs" 
					:key="index"
					class="tabbar-item" 
					@click="switchTab(tab.pagePath, index)"
				>
					<image 
						:src="currentTabIndex === index ? tab.selectedIconPath : tab.iconPath" 
						class="tabbar-icon"
					/>
					<text class="tabbar-text">
						{{ tab.text }}
					</text>
				</view>
			</view>
		</view>
		
		<!-- 权限1：新版5个tab -->
		<view v-else-if="tabbarConfig.permission === 1 && !demo" class="tabbar modern-theme">
			<view class="tabbar-container">
				<view 
					v-for="(tab, index) in tabbarConfig.tabs" 
					:key="index"
					:class="tab.isCenter ? 'scan-container' : 'tabbar-item'"
					@click="tab.isCenter ? onScanClick() : switchTab(tab.pagePath, index)"
				>
					<!-- 普通tab -->
					<template v-if="!tab.isCenter">
						<image 
							:src="currentTabIndex === index ? tab.selectedIconPath : tab.iconPath" 
							class="tabbar-icon"
						/>
						<text class="tabbar-text">
							{{ tab.text }}
						</text>
					</template>
					
					<!-- 中间扫码按钮 -->
					<template v-else>
						<view class="scan-button" :class="currentTabIndex === index ? 'scan-active' : ''">
							<image src="/static/images/shaoma.png" class="scan-icon" :class="currentTabIndex === index ? 'scan-active' : ''" />
						</view>
					</template>
				</view>
			</view>
		</view>
		
		<!-- Demo分支：新版5个tab但使用不同图标 -->
		<view v-else-if="demo" class="tabbar modern-theme">
			<view class="tabbar-container">
				<view 
					v-for="(tab, index) in demoTabConfig.tabs" 
					:key="index"
					:class="tab.isCenter ? 'scan-container' : 'tabbar-item'"
					@click="tab.isCenter ? onScanClick() : switchTab(tab.pagePath, index)"
				>
					<!-- 普通tab -->
					<template v-if="!tab.isCenter">
						<image 
							:src="currentTabIndex === index ? tab.selectedIconPath : tab.iconPath" 
							class="tabbar-icon"
						/>
						<text class="tabbar-text">
							{{ tab.text }}
						</text>
					</template>
					
					<!-- 中间扫码按钮 -->
					<template v-else>
						<view class="scan-button" :class="currentTabIndex === index ? 'scan-active' : ''">
							<image src="/static/images/shaoma2.png" class="scan-icon" :class="currentTabIndex === index ? 'scan-active' : ''" />
						</view>
					</template>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getTabbarConfig, getCurrentTabIndex, shouldShowTabbar } from '@/utils/tabbarPermission.js'
import { extractUrlParameters } from '@/utils/util'
import { getScan, anonymousScan, getCoupon } from '@/api/index/index.js'
import { getStationStartCharegDetail } from '@/api/charging/index.js'
import { openDoorForApp, openGate as apiOpenGate, openNormalDoor as apiOpenNormalDoor, openDoorByShopId as apiOpenDoorByShopId, takeEnvelopeApi } from '@/api/massageCabin'
import appConfig from '@/config/app.config.js'

export default {
	name: 'SmartTabbar',
	props: {
		// 保留active属性用于手动指定，但优先使用自动计算
		active: {
			type: Number,
			default: -1
		}
	},
	data() {
		return {
			tabbarConfig: {},
			currentRoute: '',
			shouldShow: false,
			demo: appConfig.mode.isDemo, // 从配置文件读取demo模式状态
			demoTabConfig: {
				permission: 1,
				theme: 'modern',
				tabs: [
					{
						text: "首页",
						pagePath: "pages/indexDemo/index",
						icon: "home",
						activeIcon: "home-filled",
						iconPath: "/static/images/shouye_g1.png",
						selectedIconPath: "/static/images/shouye_g.png"
					},
					{
						text: "司机生活",
						pagePath: "pages/life/life2", 
						icon: "gift",
						activeIcon: "gift-filled",
						iconPath: "/static/images/shenghuo_g1.png",
						selectedIconPath: "/static/images/shenghuo_g.png"
					},
					{
						text: "扫码",
						pagePath: "packages/oldpages/pages/scan/index",
						icon: "scan",
						activeIcon: "scan",
						isCenter: true,  // 中间特殊按钮
						iconPath: "/static/images/tab_scan.png",
						selectedIconPath: "/static/images/tab_scan_active.png"
					},
					{
						text: "积分商城",
						pagePath: "pages/shop/shop",
						icon: "shop",
						activeIcon: "shop-filled",
						iconPath: "/static/images/shangcheng_g1.png",
						selectedIconPath: "/static/images/shangcheng_g.png"
					},
					{
						text: "我的",
						pagePath: "pages/member/index",
						icon: "person",
						activeIcon: "person-filled",
						iconPath: "/static/images/wode_g1.png",
						selectedIconPath: "/static/images/wode_g.png"
					}
				]
			}
		}
	},
	computed: {
		// 当前激活的tab索引
		currentTabIndex() {
			// 如果手动指定了active且有效，使用指定值
			if (this.active >= 0) {
				return this.active;
			}
			// 否则自动计算
			return getCurrentTabIndex(this.currentRoute);
		}
	},
	created() {
		console.log('=== SmartTabbar 组件创建 ===');
		this.loadTabbarConfig();
		this.updateCurrentRoute();
	},
	methods: {
		// 加载tabbar配置
		loadTabbarConfig() {
			console.log('=== 开始加载tabbar配置 ===');
			// demo模式下写死权限为1
			if (this.demo) {
				this.tabbarConfig = {
					permission: 1,
					theme: 'modern',
					tabs: this.demoTabConfig.tabs
				};
			} else {
				this.tabbarConfig = getTabbarConfig();
			}
			console.log('获取到的tabbar配置:', JSON.stringify(this.tabbarConfig, null, 2));
			this.updateShouldShow();
			console.log('shouldShow状态:', this.shouldShow);
		},
		
		// 更新当前路由
		updateCurrentRoute() {
			console.log('=== 更新当前路由 ===');
			const pages = getCurrentPages();
			console.log('当前页面栈:', pages);
			if (pages.length > 0) {
				const currentPage = pages[pages.length - 1];
				this.currentRoute = currentPage.route;
				console.log('当前页面路由:', this.currentRoute);
				this.updateShouldShow();
			} else {
				console.log('页面栈为空，无法获取当前路由');
			}
		},
		
		// 更新是否显示tabbar
		updateShouldShow() {
			console.log('=== 更新shouldShow状态 ===');
			console.log('当前路由:', this.currentRoute);
			console.log('tabbar配置:', this.tabbarConfig);
			this.shouldShow = shouldShowTabbar(this.currentRoute);
			console.log('最终shouldShow:', this.shouldShow);
		},
		
		// 切换tab
		switchTab(pagePath, index) {
			// 如果是当前页面，不跳转
			if (this.currentRoute === pagePath) {
				return;
			}
			
			// 使用reLaunch清除页面栈并跳转
			uni.reLaunch({
				url: `/${pagePath}`,
			});
		},
		
		// 处理扫码（复用旧首页逻辑入口）
		handleScan() {
			uni.scanCode({
				success: (res) => {
					this.codehandler(res.result);
				},
				fail: (err) => {
					uni.showToast({ title: '扫码失败', icon: 'none' });
				}
			});
		},

		// 从旧首页移植：扫码结果处理
		codehandler(code) {
			if (code.includes('lixingpt.com/door') || code.includes('lixingpt.com/gate') || code.includes('lixingpt.com/shop')) {
				this.openDoor(code);
				return;
			}
			const params = extractUrlParameters(code);
			if (code.includes('lixingpt.com/scan')) {
				const opt = params['opt'];
				if (opt === 'deviceBoot') {
					this.bootDevice(params['devId']);
				} else if (opt === 'envelope') {
					this.takeTheEnvelope(code);
				}else if (opt === "getCoupon"){
					//领取优惠券的
					this.toGetCoupon(code);
				}
				return;
			}
			// 新增：非 lixingpt.com/scan 的二维码，尝试按充电二维码处理
			this.getStartChargeByQr(code);
		},

		// 新增：按充电二维码拉取启动充电前详情并跳转
		getStartChargeByQr(qrCode) {
			getStationStartCharegDetail({ qrCode }).then(res => {
				if (res && res.code === 0 && res.success) {
					const detail = res.data || {};
					const encodedDetail = encodeURIComponent(JSON.stringify(detail));
					uni.navigateTo({ url: `/pages/order/index?qrCode=${encodeURIComponent(qrCode)}&detail=${encodedDetail}` });
				} else {
					uni.showToast({ title: (res && res.msg) || '处理失败', icon: 'none' });
				}
			}).catch(err => {
				uni.showToast({ title: (err && err.msg) || '网络异常', icon: 'none' });
			});
		},

		// 旧逻辑：红包
		takeTheEnvelope(code) {
			if (uni.getStorageSync('userInfo')) {
				uni.showLoading({ title: '正在领取红包...' });
				takeEnvelopeApi(extractUrlParameters(code)).then(
					(res) => {
						uni.hideLoading();
						uni.showModal({ title: '领取成功！', content: res['data'] + '，请到“会员中心”查看。', showCancel: false, confirmText: '好的' });
					},
					(error) => {
						uni.hideLoading();
						this.showError(error);
					}
				);
			} else {
				this.saveQRAndGoToLoginPage(code);
			}
		},

		toGetCoupon(code) {
			console.log(code);
			console.log(3);
			var params = extractUrlParameters(code);
			const codeValue = params["code"];
			const promId = params["promId"];
			console.log(codeValue,promId);
			if (!codeValue || !promId) {
				wx.showToast({
					title: '二维码参数不完整',
					icon: 'error',
					duration: 2000
				});
				return;
			}
			
			wx.showLoading({
				title: '正在领取优惠券...',
			});
			
			// 调用真实接口
			getCoupon({
				code: codeValue,
				promId: promId
			}).then(res => {
				wx.hideLoading();
				if (res.success) {
					// 显示优惠券弹窗，使用接口返回的图片
					this.setData({
						showCoupon: true,
						couponImage: res.data.img
					});
				} else {
					wx.showToast({
						title: res.msg || '领取失败',
						icon: 'error',
						duration: 2000
					});
				}
			}).catch(err => {
				wx.hideLoading();
				wx.showToast({
					title: err.msg || '领取失败',
					icon: 'error',
					duration: 2000
				});
			});
		},

		// 旧逻辑：设备启动
		bootDevice(deviceId) {
			if (uni.getStorageSync('userInfo')) {
				getScan({ code: deviceId }).then((res) => {
					const data = encodeURIComponent(JSON.stringify(res.data));
					if (res.data.device.deviceType == 0 || res.data.device.deviceType == 5) {
						uni.navigateTo({ url: '/pages/massage/index?data=' + data });
					} else {
						uni.navigateTo({ url: '/pages/laundry/index?data=' + data });
					}
				});
			} else {
				anonymousScan({ code: deviceId }).then((res) => {
					const data = encodeURIComponent(JSON.stringify(res.data));
					if (res.data.device.deviceType == 0) {
						uni.navigateTo({ url: '/pages/massage/index?data=' + data + '&code=' + deviceId });
					} else {
						uni.navigateTo({ url: '/pages/laundry/index?data=' + data + '&code=' + deviceId });
					}
				});
			}
		},

		// 旧逻辑：开门
		openDoor(code) {
			const params = extractUrlParameters(code);
			if (uni.getStorageSync('userInfo')) {
				if (code.includes('lixingpt.com/door')) {
					this.doOpenNormalDoor(params['doorId']);
				} else if (code.includes('lixingpt.com/gate')) {
					this.doOpenGateDialog(params['doorId'], params['dirction']);
				} else if (code.includes('lixingpt.com/shop')) {
					this.doOpenShopDoor(params['shopId'], params['opt']);
				}
			} else {
				this.saveQRAndGoToLoginPage(code);
			}
		},

		saveQRAndGoToLoginPage(code) {
			uni.setStorageSync('scanCodeCotent', code);
			const pages = getCurrentPages();
			const currentPagePath = pages[pages.length - 1].route;
			if (currentPagePath !== '/pages/login/index') {
				uni.navigateTo({ url: '/pages/login/index' });
			}
		},

		doOpenShopDoor(shopId, opt) {
			uni.showLoading({ title: '欢迎光临,开门中..' });
			apiOpenDoorByShopId(shopId, opt).then(
				(res) => { uni.hideLoading(); this.showSuccess(); },
				(error) => { uni.hideLoading(); this.showError(error); }
			);
		},

		showError(error) {
			uni.showToast({ title: error.msg, icon: 'error', duration: 2000 });
		},
		showSuccess() {
			uni.showToast({ title: '门已开', icon: 'success', duration: 1600 });
		},
		doOpenNormalDoor(number) {
			uni.showLoading({ title: '欢迎光临,开门中..' });
			apiOpenNormalDoor(number).then(
				(res) => { uni.hideLoading(); this.showSuccess(); },
				(error) => { uni.hideLoading(); this.showError(error); }
			);
		},
		doOpenGateDialog(number, direction) {
			uni.showLoading({ title: '欢迎光临,开门中..' });
			apiOpenGate(number, direction).then(
				(res) => { uni.hideLoading(); this.showSuccess(); },
				(error) => { uni.hideLoading(); this.showError(error); }
			);
		},

		// 中心扫码按钮点击：保留样式不变，仅触发旧逻辑
		onScanClick() {
			this.handleScan();
		},

		// 刷新权限配置
		refreshPermission() {
			// 重新加载配置并立刻更新当前路由与显示状态
			this.loadTabbarConfig();
			this.updateCurrentRoute();
			this.updateShouldShow();
		}
	},
	
	// 页面显示时更新路由信息
	onShow() {
		this.updateCurrentRoute();
	}
}
</script>

<style scoped>
.smart-tabbar {
	position: fixed;
	left: 0;
	bottom: 0;
	z-index: 100;
	width: 100%;
}

.tabbar {
	height: 120rpx;
	background-color: #fff;
	border-top: 1px solid #eee;
}

/* 旧版主题 */
.classic-theme {
	box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

/* 新版主题 */
.modern-theme {
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

.tabbar-container {
	display: flex;
	align-items: center;
	justify-content: space-around;
	height: 100%;
	padding: 0 20rpx;
}

.tabbar-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	flex: 1;
	height: 100%;
	padding: 10rpx 0;
}

.tabbar-icon {
	width: 48rpx;
	height: 48rpx;
}

.tabbar-text {
	font-size: 22rpx;
	margin-top: 8rpx;
}

.text-active {
	color: #2455E1;
}

.text-default {
	color: #666;
}

/* 扫码按钮样式 */
.scan-container {
	display: flex;
	align-items: center;
	justify-content: center;
	flex: 1;
	height: 100%;
}

.scan-button {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 10rpx;
	transition: all 0.3s ease;
}

.scan-button:active {
	transform: scale(0.95);
}

.scan-active {
	background: linear-gradient(135deg, #ff6b2a, #ff8500);
	box-shadow: 0 6px 16px rgba(255, 123, 58, 0.4);
}

.scan-icon {
	width: 100rpx;
	height: 100rpx;
}
</style>